package org.dromara.common.mybatis.v1;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

public class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {
    protected Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public boolean save(T entity) {
        EntityUtils.setCreatAndUpdatInfo(entity);
        return super.save(entity);
    }

    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean saveBatch(Collection<T> entityList, int batchSize) {
        for (T entity : entityList) {
            EntityUtils.setCreatAndUpdatInfo(entity);
        }
        return super.saveBatch(entityList, batchSize);
    }

    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean saveOrUpdate(T entity) {
        EntityUtils.setCreatAndUpdatInfo(entity);
        return super.saveOrUpdate(entity);
    }

    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) {
        for (T entity : entityList) {
            EntityUtils.setCreatAndUpdatInfo(entity);
        }
        return super.saveOrUpdateBatch(entityList, batchSize);
    }

    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean updateById(T entity) {
        EntityUtils.setUpdatedInfo(entity);

        return super.updateById(entity);
    }

    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean update(T entity, Wrapper<T> updateWrapper) {
        EntityUtils.setUpdatedInfo(entity);
        return super.update(entity, updateWrapper);
    }

    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean updateBatchById(Collection<T> entityList, int batchSize) {
        for (T entity : entityList) {
            EntityUtils.setUpdatedInfo(entity);
        }

        return super.updateBatchById(entityList, batchSize);
    }


}
